<?php

namespace app\activity\controller;

use think\Controller;
use app\activity\model\Turntable as TurntableModel;
use think\Request;
use think\db;
use think\Image;

class Turntable extends Controller{

    protected $params;
    public $request;

    public function _initialize()
    {
        $this->request = Request::instance();
        $this->request->filter(['strip_tags','htmlspecialchars']);
        $this->params =  $this->request->param();
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 获取所有的转盘列表
     * @param shop_id
     * @param is_shop 非必填  1商户，0或不填为普通用户
     * @param page
     * @param page_size
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function get_all_list() {
        $params = $this->params;
        if (!isset($params['shop_id'])) {
            return resultArray(['error'=>'没有商户id']);
        }

        $isShop = empty($params['is_shop']) ? 0 : 1;
        $page = !empty($params['page']) ? $params['page'] : 0;
        $pageSize = !empty($params['page_size']) ? $params['page_size'] : 20;

        $turntableModel = new TurntableModel();
        $gameList = $turntableModel->get_all_list($params['shop_id'],$page,$pageSize,$isShop);
        foreach ($gameList as $k => $v) {
            $gameList[$k]['created'] = date('Y-m-d H:i:s',$v['created']);
            $gameList[$k]['start_date'] = date('Y-m-d H:i:s',$v['start_date']);
            $gameList[$k]['end_date'] = date('Y-m-d H:i:s',$v['end_date']);
        }
        if ($gameList) {
            return resultArray(['data' => $gameList]);
        } else {
            return resultArray(['data' => []]);
        }
    }

    /**
     * 大转盘列表接口
     * @param shop_id
     * @param turntable_id
     * @return \think\response\Json
     */
    public function get_prize_list() {
        //接口防刷验证，还没做。token检验

        $params = $this->params;
        if (empty($params['shop_id'])) {
            return resultArray(['error'=>'没有商户id']);
        }
        if (empty($params['turntable_id'])) {
            return resultArray(['error' => '没有转盘id']);
        }
        $turntableModel = new TurntableModel();

        //转盘列表
        $data = $turntableModel->get_turntable_list($params['shop_id'], $params['turntable_id']);
        if (empty($data)) {
            return resultArray(['error'=>'该转盘不存在']);
        }
        foreach ($data['list'] as $k => $v) {//过滤前端不应该显示的字段
            unset($data['list'][$k]['probability']);
            unset($data['list'][$k]['type']);
            unset($data['list'][$k]['listorder']);
            unset($data['list'][$k]['status']);
            unset($data['list'][$k]['num']);
            unset($data['list'][$k]['created']);
        }
        if ($data['start_date'] > time()) {
            $data['msg'] = "转盘活动还没开始";
            return resultArray(['data' => $data]);
//            return resultArray(['error' => '转盘活动还没开始']);
        }
        if ($data['end_date'] < time()) {
            $data['msg'] = "转盘活动已经结束";
            return resultArray(['data' => $data]);
//            return resultArray(['error' => '转盘活动已经结束']);
        }

        //用户抽奖的情况
        $userId = empty($params['user_id']) ? 0 : $params['user_id'];
        $userStatus = $turntableModel->check_user_times($params['turntable_id'],$userId,$data['num_by_one'],$data['start_date'],$data['end_date'],$data['frequncy']);
        $data['user_status'] = $userStatus;

        $data['start_date'] = date("Y-m-d H:i:s",$data['start_date']);
        $data['end_date'] = date("Y-m-d H:i:s",$data['end_date']);

        //幸运榜
        $luckyList = $turntableModel->get_lucky_list($params['turntable_id']);
        $data['lucky_list'] = $luckyList;

        return resultArray(['data'=> $data]);
    }

    /**
     * play
     * @param turntable_id
     * @param shop_id
     * @param user_id
     * @return \think\response\Json
     */
    public function play_game() {
        $params = $this->params;
        if (!IS_TRUE_NAME) {
            if (!isset($params['true_name'])) {
                return resultArray(['error'=> "用户需要完善用户名才可以使用"]);
            }
        }
        if (empty($params['turntable_id'])) {
            return resultArray(['error' => '没有转盘id']);
        }
        if (empty($params['shop_id'])) {
            return resultArray(['error'=>'没有商户id']);
        }
        if (empty($params['user_id'])) {
            return resultArray(['error'=>'没有用户id']);
        }

        $turntableModel = new TurntableModel();
        $res = $turntableModel->play($params['turntable_id'],$params['shop_id'],$params['user_id']);
        if ($res == -1) {
            return resultArray(['error'=>'转盘活动还没开始']);
        } elseif ($res == -2) {
            return resultArray(['error'=>'转盘活动已经结束']);
        } elseif ($res == -3) {
            return resultArray(['error'=>'系统繁忙,请重试']);
        } elseif ($res == -4) {
            return resultArray(['error'=>'系统异常，请联系管理员']);
        } elseif ($res == -5) {
            return resultArray(['error'=>'没有抽奖次数了']);
        } elseif ($res == -6) {
            return resultArray(['error'=>'奖品已经全部抽完']);
        } elseif ($res == -7) {
            return resultArray(['error'=>'该转盘不存在']);
        } elseif (is_array($res) && isset($res['status'])) {
            if ($res['status'] == 2) {
                $res['msg'] = "您已经中过奖了，奖项是: ".$res['prize_name'];
                return resultArray(['data'=> $res]);
            } elseif ($res['status'] == 3) {
                $res['msg'] = "您的抽奖结果是: ".$res['prize_name'];
                return resultArray(['data'=> $res]);
            }
        } else {
            return resultArray(['error'=>'未知错误']);
        }
    }


    /**
     * 商户后端
     * *******************************************************************************************************
     */

    /**
     * 新增转盘信息
     * @param 以下empty中的内容都必填
     * @param turntable_id 更新需要传
     * @return \think\response\Json
     */
    public function save() {
        $params = $this->params;

        if (empty($params['shop_id']) || empty($params['title']) || empty($params['description']) || empty($params['num_by_one']) || empty($params['listorder']) || !isset($params['status']) || empty($params['start_date']) || empty($params['end_date']) || empty($params['frequncy'])) {
            return resultArray(['error' => '上传的数据不完整']);
        }
        $insertData = array(
            'shop_id'       => intval($params['shop_id']),
            'title'         => $params['title'],
            'description'   => $params['description'],
            'num_by_one'    => intval($params['num_by_one']),
            'listorder'     => intval($params['listorder']),
            'status'        => intval($params['status']),
            'start_date'    => strtotime($params['start_date']),
            'end_date'      => strtotime($params['end_date']),
            'created'       => time(),
            'frequncy'      => intval($params['frequncy'])
        );

        $turntableModel = new TurntableModel();
        if (empty($params['turntable_id'])) { //新增操作
            $turntableId = $turntableModel->save_game($insertData);
            if ($turntableId > 0) {
                return resultArray(['data' => ['msg'=>'新增成功','turntable_id'=>$turntableId]]);
            } else {
                return resultArray(['error' => '新增失败，请重试']);
            }
        } else {//更新操作。需要turntable_id
            $insertData['updated'] = time();
            $res = $turntableModel->update_game($insertData,$params['turntable_id']);
            if (!empty($res)) {
                return resultArray(['data' => ['msg'=>'更新成功','turntable_id'=>$params['turntable_id']]]);
            } else {
                return resultArray(['error' => '更新失败，请重试']);
            }
        }
    }


    /**
     * 新增奖品信息
     * @param data json字符串
     * @return \think\response\Json
     */
    public function save_info() {
        if (!isset($_REQUEST['data'])) {
            return resultArray(['error' => '上传的数据不完整']);
        }
        $data = strip_tags($_REQUEST['data']);
        if (empty($data)) {
            return resultArray(['error' => '上传的数据不完整']);
        }
        $data = json_decode($data,true);
        foreach ($data as $k => $v) {
            $data[$k]['created'] = time();
        }
        $turntableModel = new TurntableModel();
        $res = $turntableModel->save_game_info($data);
        if (!empty($res)) {
            return resultArray(['data' => ['msg'=>'新增成功']]);
        }
        return resultArray(['error' => '新增失败，请重试']);
    }

    /**
     * 图片上传
     * @return \think\response\Json
     */
    public function upload(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('images');
        if (empty($file)) {
            return resultArray(['error' =>'没有上传图片']);
        }
        // 移动到根目录/public/uploads/ 目录下
        $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
            $filePath = $http_type.$_SERVER['HTTP_HOST']. DS . 'uploads'.DS.$info->getSaveName();
            $getInfo = $info->getInfo();
            $imgInfo = Image::open($info);
            $savePath = $info->getSaveName();
            $pathThumb = explode('.',$savePath);
            $pathThumb[0] = $pathThumb[0].'_thumb';
            $pathName = implode('.',$pathThumb);
            $pathName = 'uploads'.DS.$pathName;
            // 另存一份压缩后的图片
            $info = @$imgInfo->thumb(100, 50)->save($pathName);
            //获取图片的原名称
            $name = $getInfo['name'];
            $data = [
                'path' => $filePath,
                'path_thumb' => $http_type.$_SERVER['HTTP_HOST'] . DS .$pathName,
                'name' => $name,
                'created' => date('Y-m-d H:i:s'),
                'msg' => '图片上传成功'
            ];
            return resultArray(['data' => $data]);
        }else{
            // 上传失败获取错误信息
            return resultArray(['error' => $file->getError()]);
        }
    }

    /**
     * 更新奖品数据
     * @param id 奖品id
     * @param turntable_id
     * @return \think\response\Json
     */
    public function update_info() {
        $params = $this->params;
        if (empty($params['id'])) {
            return resultArray(['error'=>'没有奖品id']);
        }
        if (empty($params['turntable_id'])) {
            return resultArray(['error' => '没有转盘id']);
        }
        $turntableId = $params['turntable_id'];
        $prizeId = $params['id'];
        unset($params['turntable_id']);
        unset($params['id']);


        $turntableModel = new TurntableModel();
        $res = $turntableModel->update_game_info($params,$turntableId,$prizeId);
        if ($res) {
            return resultArray(['data' => "更新成功"]);
        } else {
            return resultArray(['error' => "更新失败"]);
        }
    }


    /**
     * 获取单条转盘及奖品信息
     * @param turntable_id
     * @return \think\response\Json
     */
    public function get_turntable_one() {
        $params = $this->params;
        if (empty($params['turntable_id'])) {
            return resultArray(['error' => '没有转盘id']);
        }

        $turntableModel = new TurntableModel();
        $data = $turntableModel->get_turntable_one($params['turntable_id']);
        $data['created'] = date('Y-m-d H:i:s',$data['created']);
        $data['start_date'] = date('Y-m-d H:i:s',$data['start_date']);
        $data['end_date'] = date('Y-m-d H:i:s',$data['end_date']);

        if (!empty($data)) {
            return resultArray(['data' => $data]);
        } else {
            return resultArray(['error' => "获取数据失败"]);
        }
    }

    /**
     * 商户可看到的转盘数据
     * @param shop_id
     * @param turntable_id
     * @param user_id
     * @param start_date
     * @param end_date
     * @return \think\response\Json
     */
    public function win_list() {
        $params = $this->params;
        if (empty($params['shop_id'])) {
            return resultArray(['error'=>'没有商户id']);
        }
        $turntableId = empty($params['turntable_id']) ? 0 : $params['turntable_id'];
        $userId = empty($params['user_id']) ? 0 : $params['user_id'];
        $startDate = empty($params['start_date']) ? 0 : $params['start_date'];
        $endDate = empty($params['end_date']) ? 0 : $params['end_date'];

        $turntableModel = new TurntableModel();
        $data = $turntableModel->win_list($params['shop_id'],$turntableId,$userId,$startDate,$endDate);
        foreach ($data as $k => $v) {
            $data[$k]['created'] = date("Y-m-d H:i:s",$v['created']);
        }

        if (empty($data)) {
            return resultArray(['data'=>[]]);
        }
        return resultArray(['data'=>$data]);
    }


    /**
     * 大后台数据
     * ******************************************************************************************************
     */

    /**
     * 大后台的转盘数据总览
     * @param page
     * @param page_size
     * @param start_date,end_date,status,created 这几个字段是搜索字段
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function get_list_for_bk() {
        $params = $this->params;

        $page = !empty($params['page']) ? $params['page'] : 0;
        $pageSize = !empty($params['page_size']) ? $params['page_size'] : 20;
        $turntableModel = new TurntableModel();

        $data = $turntableModel->get_list_for_bk($page,$pageSize,$params);

        if ($data) {
            return resultArray(['data'=> $data]);
        }

        return resultArray(['data'=> []]);
    }

    /**
     * 奖品列表。包含每个奖品对应的中奖人数
     * @param turntable_id
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function prize_list_for_bk() {
        $params = $this->params;
        if (empty($params['turntable_id'])) {
            return resultArray(['error' => '没有转盘id']);
        }
        $turntableId = $params['turntable_id'];
        $turntableModel = new TurntableModel();
        $data = $turntableModel->prize_list_for_bk($turntableId);

        if ($data) {
            return resultArray(['data'=> $data]);
        }

        return resultArray(['data'=> []]);

    }

    /**中奖列表。每个奖品中的奖品
     * @param prize_id 奖品id
     * @param turntable_id
     * @return \think\response\Json
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function win_list_for_bk() {
        $params = $this->params;

        if (empty($params['prize_id'])) {
            return resultArray(['error' => '没有奖品id']);
        }
        if (empty($params['turntable_id'])) {
            return resultArray(['error' => '没有转盘id']);
        }
        $page = !empty($params['page']) ? $params['page'] : 0;
        $pageSize = !empty($params['page_size']) ? $params['page_size'] : 20;
        $turntableModel = new TurntableModel();

        $data = $turntableModel->win_list_for_bk($params['prize_id'],$params['turntable_id'],$page,$pageSize);

        if ($data) {
            return resultArray(['data'=> $data]);
        }

        return resultArray(['data'=> []]);
    }


}

